// 导入http
import { Http } from "../../../http/users"
import { ref } from "vue"
import { ElMessage } from "element-plus"
//保存页码
const page = ref(1)
// 保存偏移量
const offset = ref(5)
//保存搜索框内容
const content = ref("")
//存放用户数据
const members = ref([])
//存放用户总数
const total = ref(0)
//控制对话框显隐
const dialogVisible = ref(false)
//控制对话框的标题
const dialogTitle = ref("添加用户")
//定义表单数据
const userForm = ref({
  username: "",
  password: "",
  type: 0,
  id: 0,
})
//定义表单ref
const userFormRef = ref()
//定义表单规则
const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 8, message: "长度在4~8个字符之间", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 4, max: 16, message: "长度在4~16个字符之间", trigger: "blur" },
  ],
}
//保存管理员勾选的用户(用于注销)
const ids = ref([])
//记录是否在搜索状态
const flag = ref(false)
//显示用户数据函数,复用
async function getAllMembers(nowPage) {
  //请求交通部门用户数据
  let data1 = await Http.getTrafficMembers({
    page: page.value,
    offset: offset.value,
  })
  // 请求普通用户数据
  let data2 = await Http.getNormalMembers({
    page: page.value,
    offset: offset.value,
  })
  if (nowPage == "traffic") {
    //交通部门用户数据
    members.value = data1.result.data
    total.value = data1.result.total
  } else {
    //普通用户数据
    members.value = data2.result.data
    total.value = data2.result.total
  }
}
export const useGetUsers = (nowPage) => {
  getAllMembers(nowPage)
  /* 分页功能 */
  //切换页码函数
  const handleCurrentChange = async (s) => {
    // let data
    page.value = s
    if (flag.value == true) {
      searchContent()
    } else {
      getAllMembers(nowPage)
    }
    // getAllMembers(nowPage)
  }
  //切换偏移量函数
  const handleSizeChange = async (s) => {
    offset.value = s
    if (flag.value == true) {
      searchContent()
    } else {
      getAllMembers(nowPage)
    }
    // getAllMembers(nowPage)
  }
  //搜索功能
  const handleSearch = async () => {
    let data
    flag.value = true
    if (content.value == "") {
      ElMessage.error("搜索内容不能为空")
    } else {
      //发送请求获取数据
      if (nowPage == "traffic") {
        data = await Http.getSearch({
          keyword: content.value,
          type: 1,
        })
      } else {
        data = await Http.getSearch({
          keyword: content.value,
          type: 0,
        })
      }
      total.value = data.result.total
      members.value = data.result.data
      // content.value = ""
    }
  }
  // 显示全部功能
  const handleShowAll = async () => {
    flag.value = false
    getAllMembers(nowPage)
  }
  //添加用户功能
  const handleAdd = () => {
    dialogTitle.value = "添加用户"
    dialogVisible.value = true
    userForm.value.username = ""
    userForm.value.password = ""
  }
  //管理用户功能
  const handleOperator = (id, username, password) => {
    dialogVisible.value = true
    dialogTitle.value = "管理用户"
    userForm.value.id = id
    userForm.value.username = username
    userForm.value.password = password
  }
  //提交用户信息函数
  const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate(async (valid, fields) => {
      if (valid) {
        //当为添加用户时
        let data
        if (dialogTitle.value == "添加用户") {
          //当添加交通部门人员时
          if (nowPage == "traffic") {
            data = await Http.addUsers({
              username: userForm.value.username,
              password: userForm.value.password,
              type: 1,
            })
          } else {
            //当添加普通用户时
            data = await Http.addUsers({
              username: userForm.value.username,
              password: userForm.value.password,
              type: 0,
            })
          }
          if (data.code == 201) {
            ElMessage.error("用户名已占用,请重新输入")
            return
          } else {
            ElMessage.success("添加用户成功")
          }
          //当为管理用户时
        } else {
          //当管理交通部门时
          if (nowPage == "traffic") {
            data = Http.updateUsers(userForm.value.id, {
              username: userForm.value.username,
              password: userForm.value.password,
              type: 1,
            })
          } else {
            data = Http.updateUsers(userForm.value.id, {
              username: userForm.value.username,
              password: userForm.value.password,
              type: 0,
            })
          }
          if (data.code == 201) {
            ElMessage.error("用户名已占用,请重新输入")
            return
          } else {
            ElMessage.success("管理用户信息成功")
          }
        }
        getAllMembers(nowPage)
        dialogVisible.value = false
        userForm.value.username = ""
        userForm.value.password = ""
      } else {
        ElMessage.error("格式错误,请重新输入")
      }
    })
  }
  //管理用户权限
  const changePower = async (id, type) => {
    let data
    // 当为交通管理员时,降级
    if (type == 1) {
      data = await Http.updatePower(id, { type: 0 })
    } else {
      //当为普通管理员时,升级
      data = await Http.updatePower(id, { type: 1 })
    }
    if (data.code == 200) {
      ElMessage.success("修改用户权限成功")
    } else {
      ElMessage.success("修改用户权限失败")
    }
    getAllMembers(nowPage)
  }
  //强制用户下线
  const handleOutLine = async (id) => {
    let data = await Http.underLine(id)
    console.log(id)
    if (data.code == 200) {
      ElMessage.success("强制用户下线成功")
    } else {
      ElMessage.success("强制用户下线失败")
    }
    getAllMembers(nowPage)
  }
  //注销用户(单选)
  const handleSelect = (selection, row) => {
    if (ids.value.length != 0) {
      ids.value = []
    }
    selection.forEach((item) => {
      ids.value.push(item.id)
    })
  }
  //注销用户(全选)
  const handleSelectAll = (selection) => {
    if (ids.value.length != 0) {
      ids.value = []
    }
    selection.forEach((item) => {
      ids.value.push(item.id)
    })
  }
  //执行注销操作
  const handleDelete = async () => {
    let str = ids.value.join(",")
    console.log(str)
    //发送请求,注销
    let data = await Http.deleteUsers(str)
    if (data.code == 200) {
      ElMessage.success("注销用户成功")
    } else {
      ElMessage.error("注销用户失败")
    }
    getAllMembers(nowPage)
  }
  //留存搜索内容
  async function searchContent() {
    //发送请求获取数据
    if (nowPage == "traffic") {
      data = await Http.getSearch({
        keyword: content.value,
        type: 1,
      })
    } else {
      data = await Http.getSearch({
        keyword: content.value,
        type: 0,
      })
    }
    total.value = data.result.total
    members.value = data.result.data
  }
  //导出
  return {
    members,
    total,
    page,
    offset,
    handleCurrentChange,
    handleSizeChange,
    content,
    handleSearch,
    handleShowAll,
    handleOperator,
    dialogVisible,
    dialogTitle,
    userForm,
    rules,
    submitForm,
    userFormRef,
    handleAdd,
    changePower,
    handleOutLine,
    handleSelect,
    handleSelectAll,
    handleDelete,
  }
}
